package com.sansan.qiangji.realize.base;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.sansan.qiangji.dto.ProductExcelDto;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ProductExcelListener extends AnalysisEventListener<ProductExcelDto> {
    private ProductReal productReal;
    List<ProductExcelDto> productExcelDtos = new ArrayList<>();

    public ProductExcelListener(ProductReal productReal) {
        this.productReal = productReal;
    }

    @Override
    public void invoke(ProductExcelDto productExcelDto, AnalysisContext analysisContext) {
        if (productExcelDto.getProductCode() == null || productExcelDto.getProductCode().equals("")){
            log.error("【上传物料表格】物料编号不能为空");
            ReadRowHolder readRowHolder = analysisContext.readRowHolder();
            int rowIndex = readRowHolder.getRowIndex()+1;
            throw new ServiceException(ResultEnum.PRODUCT_NAME_NOT_EMPTY.getCode(), "第 "+ rowIndex +" 行物料编号不能为空！");
        }
        if (productExcelDto.getProductName() == null || productExcelDto.getProductName().equals("")){
            log.error("【上传物料表格】物料名称不能为空");
            ReadRowHolder readRowHolder = analysisContext.readRowHolder();
            int rowIndex = readRowHolder.getRowIndex()+1;
            throw new ServiceException(ResultEnum.PRODUCT_NAME_NOT_EMPTY.getCode(), "第 "+ rowIndex +" 行物料名称不能为空！");
        }
        productExcelDtos.add(productExcelDto);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        productReal.upLoadProductExcel(productExcelDtos);
    }
}
